<template>
  <div :id="id" :style="{ height:height,width:width }" />
</template>

<script>
import echarts from "echarts";
export default {
  props: {
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "1270px",
    },
    data: {
      type: Array,
      default: () => [],
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chart: null,
      legendData: [],
      echartData: [],
      plusImg:
        "path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z",
      minusImg:
        "path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h368c4.4 0 8 3.6 8 8v48z",
      emptyImg: "circle",
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      // 这里我选的图片是透明背景的，如果使用白色背景的图片就可以遮盖节点后的线条了
      let plusImg =
        "";

      let minusImg =
        "";

      let emptyImg =
        "";

      // 获取节点显示的图片
      const getSymbolImg = (item = {}) => {
        return `image://${
          item.children && item.children.length
            ? minusImg
            : item.children_bak && item.children_bak.length
            ? plusImg
            : emptyImg
        }`;
      };

      // 基础配置option
      const commonOption = {
        animation: false,
        series: [
          {
            type: "tree",
            left: "18%",
            right: "20%",
            top: "1%",
            bottom: "2%",
            orient: "LR", //方向
            // initialTreeDepth: 1, //深度
            symbol: "circle",
            symbolSize: 20,
            itemStyle: {
              color: "#ffad3d",
              borderColor: "rgba(255,255,255,.1)",
            },

            lineStyle: {
              width: 1,
              curveness: 0.5,
            },
            label: {
              normal: {
                position: "left",
                verticalAlign: "middle",
                distance: 70,
                align: "center",
                backgroundColor: "#1678fd",
                color: "#fff",
                padding: [10, 10, 10, 10],
                borderRadius: 15,
                width: 100,
                formatter: function (params) {
                  console.log(params);
                  return params.name
                    .replace(/[^\x00-\xff]/g, "$&\x01")
                    .replace(/.{12}\x01?/g, "$&\n")
                    .replace(/\x01/g, "");
                },
                rich: {
                  box: {
                    height: 30,
                    color: "#fff",
                    align: "center",
                    borderRadius: 30,
                  },
                },
              },
            },
            leaves: {
              label: {
                normal: {
                  formatter: function (params) {
                    return params.name
                    .replace(/[^\x00-\xff]/g, "$&\x01")
                    .replace(/.{24}\x01?/g, "$&\n")
                    .replace(/\x01/g, "");
                  },
                  position: "right",
                  verticalAlign: "middle",
                  distance: 0,
                  align: "left",
                  color: "#000",
                  backgroundColor: "rgba(255,255,255,.1)",
                  rich: {
                    box: {
                      height: 18,
                      color: "#333",
                      align: "center",
                    },
                  },
                },
              },
              symbolOffset: [8, 0],
            },
          },
        ],
      };

      // 原始数据
      const respData = [
        {
          name: "百度在线网络技术（北京）有限公司",
          id: 1,
          backgroundColor: "#ffad3d",
          level: 0,
        },
        {
          id: 2,
          name: "产品部",
          level: 1,
          backgroundColor: "#1678fd",
          parent_node_id: 1,
        },
        {
          id: 3,
          name: "研发部",
          level: 1,
          backgroundColor: "#ffad3d",
          parent_node_id: 1,
        },
        {
          id: 4,
          name: "前端开发",
          level: 2,
          parent_node_id: 3,
        },
        {
          id: 5,
          name: "后端开发",
          level: 2,
          parent_node_id: 3,
        },
        {
          id: 6,
          name: "算法",
          level: 2,
          parent_node_id: 3,
        },
       {
          id: 7,
          name: "测试部",
          level: 2,
          parent_node_id: 3,
        },
        {
          id: 8,
          name: "运维",
          level: 2,
          parent_node_id: 3,
        },
        {
          id: 9,
          name: "运营",
          level: 1,
          backgroundColor: "#ffad3d",
          parent_node_id: 1,
        },
        {
          id: 10,
          name: "运营-1部",
          level: 2,
          parent_node_id: 9,
        },
        {
          id: 11,
          name: "运营-2部",
          level: 2,
          parent_node_id: 9,
        },
        {
          id: 12,
          name: "产品-1部产品-1部产品-1部产品-1部产品-1部产品-1部产品-1部",
          level: 2,
          parent_node_id: 2,
        },
        {
          id: 13,
          name: "产品-2部",
          level: 2,
          parent_node_id: 2,
        },
      ]
      const originalData = []
      respData.forEach((item,index)=>{
        originalData[item.id] = item
      })
      console.log(originalData)
      // 数据处理
      const innerData = [];
      Object.values(originalData).forEach((item, index) => {
        if (innerData[item.level] && innerData[item.level].length) {
          innerData[item.level].push(item);
        } else {
          innerData[item.level] = [item];
        }
      });
      console.log(innerData);
      for (let i = innerData.length - 1; i >= 0; i--) {
        // 每个item和result中的每个对象是同一引用
        innerData[i].forEach((item, index, all) => {
          item.close = function (state) {
            if (this.children) {
              if (this.children_bak.length) {
                if (state === true || this.children.length) {
                  this.children = [];
                  this.children_bak.forEach((child) => {
                    child.close(true);
                  });
                } else {
                  this.children = this.children_bak;
                }
                this.symbol = getSymbolImg(this);
                console.log(this);
              }
            }
          };
          if (i !== innerData.length - 1) {
            item.children = [];
            item.children_bak = [];
            item.add = function (it) {
              if (!!it) {
                this.children.push(it);
                this.children_bak.push(it);
              }
            };
            innerData[i + 1].forEach((child) => {
              if (+child.parent_node_id === +item.id) {
                item.add(child);
              }
            });
          }
          if (i === 0) {
            item.label = {
              normal: {
                rotate: 0,
                align: "center",
                formatter: function (params) {
                  console.log(params);
                  return params.name
                    .replace(/[^\x00-\xff]/g, "$&\x01")
                    .replace(/.{12}\x01?/g, "$&\n")
                    .replace(/\x01/g, "");
                },
              },
            };
          } else {
            if(item.level!==2){
                 item.label = {
                  backgroundColor: item.backgroundColor,
                  position: 'left',
                  verticalAlign: 'middle',
                  distance:70,
                  align: 'center',
                  color: '#fff',
                };
            }else {
              item.label = {
                  backgroundColor: 'transparent',
                };
            }
          }
          item.symbol = getSymbolImg(item);
        });
      }

      // 单个节点的点击事件
      const clickFun = (param) => {
        //因为保存了对象同一引用，所以可以使用originalData快速找到目标对象
        let aimObj = originalData[param.data.id];
        console.log(originalData[param.data.id]);
        // 组合模式实现关闭开启
        aimObj.close();
        // 手动关闭tooltip不然会出现不可关闭的tooltip
        this.chart.dispatchAction({
          type: "hideTip",
        });
        this.chart.clear();
        commonOption.series[0].data = innerData[0];
        if (originalData[param.data.id].children) {
          if (originalData[param.data.id].children.length === 0) {
            if (originalData[param.data.id].level === 0) {
              commonOption.series[0].leaves.label.normal.position = "left";
              commonOption.series[0].leaves.label.normal.distance = 50;
            }
          } else {
            commonOption.series[0].leaves.label.normal.position = "right";
            commonOption.series[0].leaves.label.normal.distance = 0;
          }
        }
        this.chart.setOption(commonOption, true);
      };

      commonOption.series[0].data = innerData[0];
      this.chart.setOption(commonOption, true);

      this.chart.on("click", clickFun);
    },
  },
};
</script>